﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;
using EffiProz.Core.Results;

namespace EffiProz.Core
{
    public class FunctionSQLInvoked : Expression
    {
        public RoutineSchema routineSchema;
        public Routine routine;

        public FunctionSQLInvoked(RoutineSchema routineSchema)
            : base(OpTypes.FUNCTION)
        {

            this.routineSchema = routineSchema;
        }

        public void setArguments(Expression[] newNodes)
        {
            this.nodes = newNodes;
        }

        public override  void resolveTypes(Session session, Expression parent)
        {

            SqlType[] types = new SqlType[nodes.Length];

            for (int i = 0; i < nodes.Length; i++)
            {
                Expression e = nodes[i];

                e.resolveTypes(session, this);

                types[i] = e.dataType;
            }

            routine = routineSchema.getSpecificRoutine(types);

            for (int i = 0; i < nodes.Length; i++)
            {
                if (nodes[i].dataType == null)
                {
                    nodes[i].dataType = routine.getParameterTypes()[i];
                }
            }

            dataType = routine.getReturnType();
        }

        public override  Object getValue(Session session)
        {

            int variableCount = routine.getVariableCount();
            Result result;
            int extraArg = routine.javaMethodWithConnection ? 1
                                                                    : 0;
            Object[] data = new object[0];
            Object returnValue = null;
            bool push = routine.isPSM() || routine.dataImpact != Routine.NO_SQL;

            if (extraArg + nodes.Length > 0)
            {
                data = new Object[nodes.Length + extraArg];

                if (extraArg > 0)
                {
                    data[0] = session.getInternalConnection();
                }
            }

            for (int i = 0; i < nodes.Length; i++)
            {
                Expression e = nodes[i];
                Object value = e.getValue(session, e.dataType);

                if (value == null)
                {
                    if (routine.isNullInputOutput())
                    {
                        return null;
                    }

                    if (!routine.getParameter(i).isNullable())
                    {
                        throw Error.error(ErrorCode.X_39004);
                    }
                }

                if (routine.isPSM())
                {
                    data[i] = value;                    
                }
                else
                {
                    data[i + extraArg] = e.dataType.convertSQLToCSharp(session,
                            value);
                }
            }

            if (push)
            {
                session.sessionContext.push();
            }

            if (routine.isPSM())
            {
                session.sessionContext.routineArguments = data;
                session.sessionContext.routineVariables =
                    new object[0];

                if (variableCount > 0)
                {
                    session.sessionContext.routineVariables =
                        new Object[variableCount];
                }

                result = routine.statement.execute(session);

                if (result.isError()) { }
                else if (result.isSimpleValue())
                {
                    returnValue = result.getValueObject();
                    returnValue = dataType.convertCSharpToSQL(session,
                                returnValue);
                }
                else
                {
                    result = Result.newErrorResult(
                        Error.error(ErrorCode.X_2F005, routine.getName().name),
                        null);
                }
            }
            else
            {
                try
                {
                    returnValue = routine.cSharpMethod.Invoke(null, data);

                    if (routine.returnsTable())
                    {

                        // convert ResultSet to table
                    }
                    else
                    {
                        returnValue = dataType.convertCSharpToSQL(session,
                                returnValue);
                    }

                    result = Result.updateZeroResult;
                }
                catch (TargetInvocationException )
                {
                    result = Result.newErrorResult(
                        Error.error(ErrorCode.X_46000, routine.getName().name),
                        null);
                }
                catch (MethodAccessException)
                {
                    result = Result.newErrorResult(
                        Error.error(ErrorCode.X_46000, routine.getName().name),
                        null);
                }
                catch (Exception )
                {
                    result = Result.newErrorResult(
                        Error.error(ErrorCode.X_46000, routine.getName().name),
                        null);
                }
            }

            if (push)
            {
                if (result.isError())
                {
                    session.rollbackToSavepoint();
                }

                session.sessionContext.pop();
            }

            if (result.isError())
            {
                throw result.getException();
            }

            return returnValue;
        }

        public override String getSQL()
        {
            return Tokens.T_FUNCTION;
        }

        public override String describe(Session session)
        {
            return base.describe(session);
        }
    }
}
